<template>
  <view class="income-detail-page">
    <view class="page-header">
      <text class="page-title">收入记录详情</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleBack">返回</button>
        <button class="btn btn-primary" @click="handleEdit" v-if="income.status === 1">编辑</button>
        <button class="btn btn-danger" @click="handleDelete">删除</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">基本信息</text>
          <view :class="['status-badge', getStatusClass(income.status)]">
            {{ getStatusText(income.status) }}
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">员工</text>
            <text class="value highlight">{{ income.staff_name || income.user_id || '-' }}</text>
          </view>
          
          <view class="detail-row" v-if="income.staff_role_text">
            <text class="label">员工职务</text>
            <text class="value">{{ income.staff_role_text }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">所属月份</text>
            <text class="value">{{ income.year_month || '-' }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">收入明细</text>
        </view>
        <view class="card-body">
          <view class="income-item">
            <text class="income-label">基本工资</text>
            <text class="income-value positive">+¥{{ income.base_salary || 0 }}</text>
          </view>
          
          <view class="income-item">
            <text class="income-label">提成金额</text>
            <text class="income-value positive">+¥{{ income.commission_amount || 0 }}</text>
          </view>
          
          <view class="income-item">
            <text class="income-label">奖金</text>
            <text class="income-value positive">+¥{{ income.bonus_amount || 0 }}</text>
          </view>
          
          <view class="income-item">
            <text class="income-label">扣款</text>
            <text class="income-value negative">-¥{{ income.deduction_amount || 0 }}</text>
          </view>
          
          <view class="income-item">
            <text class="income-label">分红</text>
            <text class="income-value positive">+¥{{ income.dividend_amount || 0 }}</text>
          </view>
          
          <view class="divider"></view>
          
          <view class="income-item total">
            <text class="income-label">总收入</text>
            <text class="income-value highlight">¥{{ income.total_income || 0 }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card" v-if="income.remarks">
        <view class="card-header">
          <text class="card-title">备注信息</text>
        </view>
        <view class="card-body">
          <text class="remark-text">{{ income.remarks }}</text>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">创建人</text>
            <text class="value">{{ income.created_by || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(income.create_time) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">更新时间</text>
            <text class="value">{{ formatTime(income.update_time) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const loading = ref(true)
const incomeId = ref('')
const income = reactive({
  user_id: '',
  staff_name: '',
  staff_role_text: '',
  year_month: '',
  base_salary: 0,
  commission_amount: 0,
  bonus_amount: 0,
  deduction_amount: 0,
  dividend_amount: 0,
  total_income: 0,
  remarks: '',
  created_by: '',
  status: 1,
  create_time: null,
  update_time: null
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  incomeId.value = currentPage.options.id || ''
  
  if (!incomeId.value) {
    uni.showToast({ title: '缺少收入记录ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/income_records/list' })
    }, 1500)
    return
  }
  
  await loadIncomeData()
  loading.value = false
})

async function loadIncomeData() {
  try {
    // 调用云对象方法获取收入记录信息
    const incomeRecordsObj = uniCloud.importObject('dh-income_records')
    const result = await incomeRecordsObj.getIncomeRecordById(incomeId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(income, result.data)
    } else {
      throw new Error(result.message || '收入记录不存在')
    }
  } catch (err) {
    console.error('加载收入记录失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/income_records/list' })
    }, 1500)
  }
}

function getStatusText(status) {
  const statusMap = {
    1: '草稿',
    2: '已审批',
    3: '已发放'
  }
  return statusMap[status] || '未知'
}

function getStatusClass(status) {
  const classMap = {
    1: 'status-draft',
    2: 'status-approved',
    3: 'status-paid'
  }
  return classMap[status] || ''
}

function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

function handleBack() {
  uni.redirectTo({ url: '/pages/business/income_records/list' })
}

function handleEdit() {
  uni.redirectTo({ url: `/pages/business/income_records/edit?id=${incomeId.value}` })
}

function handleDelete() {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条收入记录吗？此操作不可撤销。',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '删除中...' })
          // 调用云对象方法软删除收入记录
          const incomeRecordsObj = uniCloud.importObject('dh-income_records')
          const result = await incomeRecordsObj.deleteIncomeRecord(incomeId.value, '详情页删除')
          uni.hideLoading()
          if (result.code === 200) {
            uni.showToast({ title: result.message || '删除成功', icon: 'success' })
          } else {
            uni.showToast({ title: result.message || '删除失败', icon: 'none' })
            return
          }
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/business/income_records/list' })
          }, 1500)
        } catch (err) {
          console.error('删除失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '删除失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.income-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-danger {
    background: #ff3b30;
    color: #fff;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .btn {
    flex: 1;
    min-width: 0;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.status-draft {
    background: #e3f2fd;
    color: #1976d2;
  }
  
  &.status-approved {
    background: #fff3e0;
    color: #e65100;
  }
  
  &.status-paid {
    background: #e8f5e9;
    color: #2e7d32;
  }
}

.card-body {
  padding: 32rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  color: #999;
  min-width: 180rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
  
  &.highlight {
    font-size: 32rpx;
    font-weight: bold;
    color: #007aff;
  }
}

.income-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &.total {
    border-bottom: none;
    padding-top: 24rpx;
  }
}

.income-label {
  font-size: 28rpx;
  color: #666;
}

.income-value {
  font-size: 32rpx;
  font-weight: bold;
  
  &.positive {
    color: #4caf50;
  }
  
  &.negative {
    color: #f44336;
  }
  
  &.highlight {
    font-size: 48rpx;
    color: #2e7d32;
  }
}

.divider {
  height: 2rpx;
  background: #007aff;
  margin: 16rpx 0;
}

.remark-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}
</style>
